package com.zx.flow.core.execute.eventhandler;


import com.zx.flow.api.config.FlowConfig;
import com.zx.flow.api.config.FlowConfigNode;
import com.zx.flow.api.dict.FlowDict.Event;
import com.zx.flow.api.execute.model.FlowContext;
import com.zx.flow.api.execute.model.FlowNode;
import com.zx.flow.api.execute.request.FlowParamNodeEntry;
import com.zx.flow.api.execute.request.FlowParamSubFlow;
import com.zx.flow.api.execute.response.FlowResult;
import com.zx.flow.api.util.FlowDataUtil;
import com.zx.flow.core.execute.EventHandler;

/**
 * 事件处理器【流程->进入节点】
 */
public class EventFlowNodeEntryHandler extends EventHandler<FlowParamNodeEntry> {

    @Override
    public boolean in(FlowContext flow, FlowParamNodeEntry param) {
        return flow != null;
    }

    @Override
    public FlowResult on(FlowContext flow, FlowParamNodeEntry param) {
        FlowConfig config = this.getFlowConfig(flow.getFlowConfigCode(), flow.getFlowConfigId());
        FlowConfigNode entryNodeConfig = config.getNode(param.getNodeCode());
        // 创建节点信息
        FlowNode entryNode = FlowDataUtil.nodeCreate(flow, entryNodeConfig, param.getOperators(),
                param.getNodeFormId());
        // 添加一个流程节点
        flow.getNodes().add(entryNode);
        flow.setCurrentNodeCode(entryNode.getNodeCurrentCode());
        // 保存数据
        this.saveNode(flow.getId(), entryNode);
        this.saveFlow(flow);
        // 触发监听
        this.listener(entryNode, Event.nodeEntry);

        // 开启子流程
        if (entryNodeConfig.startSubFlow()) {
            flow = this.execute(new FlowParamSubFlow(flow, entryNode.getId())).getFlowContext();
        }

        return FlowResult.ok(flow);
    }
}
